package com.wbdgj.ui.tatter;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.adapter.TatterItemAdapter;
import com.wbdgj.adapter.TatterTypeAdapter;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.ui.coupon.CouponDetailAbleActivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.utils.MyGridView;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

public class TatterActivity extends BaseActivity implements PtrHandler {

    private Context context = this;
    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;

    @BindView(R.id.codeGridview)
    GridView codeGridview;
     @BindView(R.id.spGridView)
     MyGridView spGridView;
    @BindView(R.id.ljheBtn)
    Button ljheBtn;

    @BindView(R.id.rule_intro)
    TextView rule_intro;

    @BindView(R.id.hcfsTxt)
    TextView hcfsTxt;
    @BindView(R.id.hcfsContent)
    TextView hcfsContent;

    TatterItemAdapter tatterItemAdapter;
    private List<LinkedTreeMap> tatterItemList;

    TatterTypeAdapter tatterTypeAdapter;
    private List<LinkedTreeMap> tatterList;
    private String[] KEYS;

    private String M_KEY;
    private String rule_title;

    private int left_quantity;
    private int coupon_num;
    private String rule_code;
    private DecimalFormat decimalFormat;
    private boolean ljhcBoolean = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_tatter;
    }

    @Override
    protected void initView() {
        decimalFormat = new DecimalFormat("###################.###########");
        M_KEY = getIntent().getStringExtra("id");
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);
        validate();

        codeGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                tatterTypeAdapter = new TatterTypeAdapter(context, tatterList , i+"");
                codeGridview.setAdapter(tatterTypeAdapter);
                rule_code = tatterList.get(i).get("rule_code")+"";
                rule_title = tatterList.get(i).get("rule_title")+"";
                find(rule_code, rule_title);
            }
        });
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        find(rule_code, rule_title);
        pfl_root.refreshComplete();
    }

    @OnClick(value = {R.id.ljheBtn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ljheBtn:
                if (ljhcBoolean){
                    ToastUtils.toastShort("碎片不足，无法进行合成！");
                    return;
                }
//                Log.e("zp",Arrays.toString(KEYS).replace("[", "").replace("]","").replace(" ",""));
                single();
                break;
        }
    }

    private void single() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().single(rule_code, Arrays.toString(KEYS).replace("[", "").replace("]","").replace(" ",""), BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    final LinkedTreeMap linkedTreeMapDate = (LinkedTreeMap) linkedTreeMap.get("data");
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context,linkedTreeMap.get("msg")+",恭喜您获得一张"+linkedTreeMapDate.get("type_name"), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                            startActivityForResult(new Intent(context, CouponDetailAbleActivity.class).putExtra("id", linkedTreeMapDate.get("m_key")+""), 1);
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });

                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context,userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    private void validate() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().validate(M_KEY, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    tatterList = new ArrayList<>();
                    tatterList = (List<LinkedTreeMap>) linkedTreeMap.get("data");
                    tatterTypeAdapter = new TatterTypeAdapter(context, tatterList, "0");
                    codeGridview.setAdapter(tatterTypeAdapter);
                    if (tatterList.size()>0){
                        rule_code = tatterList.get(0).get("rule_code")+"";
                        rule_title = tatterList.get(0).get("rule_title")+"";
                        find(rule_code, rule_title);
                    }
                 }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void find(String rule_code, final String rule_title) {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().find(rule_code, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    LinkedTreeMap linkedTreeMapData = (LinkedTreeMap) linkedTreeMap.get("data");
                    rule_intro.setText(linkedTreeMapData.get("rule_intro")+"");
                    hcfsTxt.setText(linkedTreeMapData.get("rule_title")+"合成方式");
                    hcfsContent.setText(linkedTreeMapData.get("rule_content")+"");
                    left_quantity = 0;
                    List<LinkedTreeMap> couponList = (List<LinkedTreeMap>) linkedTreeMap.get("coupon");
                    List<LinkedTreeMap> material_package = (List<LinkedTreeMap>) linkedTreeMapData.get("material_package");
                    if (material_package.size()>0){
                        for (int i = 0; i < material_package.size() ; i ++){
                            left_quantity = left_quantity + Integer.parseInt(decimalFormat.format(material_package.get(i).get("left_quantity")));
                        }
                    }else{
                        left_quantity = 0;
                    }
                    coupon_num = couponList.size();
                    if (coupon_num >= left_quantity){
                        ljhcBoolean = false;
                        ljheBtn.setBackgroundResource(R.mipmap.tatter_button_true);
                        ljheBtn.setTextColor(getResources().getColor(R.color.colorBtnTatter));
                        KEYS = new String[left_quantity];
                        for (int i = 0; i < left_quantity; i ++){
                            KEYS[i] = couponList.get(i).get("M_KEY")+"";
                        }
                    }else{
                        ljhcBoolean = true;
                        ljheBtn.setBackgroundResource(R.mipmap.tatter_button_false);
                        ljheBtn.setTextColor(getResources().getColor(R.color.white));
                    }
                    tatterItemList = new ArrayList<>();
                    for (int i = 0; i < left_quantity ; i ++){
                        LinkedTreeMap link = new LinkedTreeMap();
                        tatterItemList.add(link);
                    }

                    tatterItemAdapter = new TatterItemAdapter(context, tatterItemList,rule_title, coupon_num);
                    spGridView.setAdapter(tatterItemAdapter);
//                    tatterList = new ArrayList<>();
//                    tatterList = (List<LinkedTreeMap>) linkedTreeMap.get("data");
//                    tatterTypeAdapter = new TatterTypeAdapter(context, tatterList, "0");
//                    codeGridview.setAdapter(tatterTypeAdapter);
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 0){
            setResult(1);
            finish();
        }
    }
}
